<?php

class User
{
    /**
     * @var object Zend DB Adapter
     */
    private $_db;
    /**
     * @var string
     */
   
    public function __construct()
    {
		$this->_db = Zend_Registry::get('db');
    }
	
	public function getModules()
	{
		if ($handle = opendir('../application/admin/controllers')) {
			/* This is the correct way to loop over the directory. */
			while (false !== ($file = readdir($handle))) {
				if ($file != "." && $file != "..") {					
					$file_array = explode('.', $file);
					$filename = $file_array[0];					
					$filename = preg_replace("(Controller)", '', $filename);
					//$filename = preg_replace("(Index)", '', $filename);					
					$modules[] = $filename;
					sort($modules);										
				}
			}

			closedir($handle);
		}
		//unset($modules[0]);
		
		return $modules;
	}
	
	public function viewUsers()
	{
		//$user_level = Zend_Auth::getInstance()->getStorage()->read()->id_member;
		$getUsers = $this->_db->fetchAll("
			SELECT userid, firstname, lastname, nickname, password, email_address, date_created, is_login, status
			FROM user
			WHERE userlevel != 'superadmin'
		");
		
		return $getUsers;
	}
	
	public function addUser($form_values)
	{
		$firstname = $form_values['firstname'];
		$lastname = $form_values['lastname']; 
		$email = $form_values['email'];
		$nickname = $form_values['username']; 
		$password = md5($form_values['password']);	
		$user_type = $form_values['userlevel'];
		$status = $form_values['status'];
		$add_user = $this->_db->exec("INSERT INTO user(firstname, lastname, nickname, password, email_address, primary_lang, date_created, userlevel, is_login, status)
						VALUES('" . $firstname . "', '" . $lastname . "', '" . $nickname . "', '" . $password . "', '" . $email . "', 'en', now(), '" . $user_type . "', 0, " . $status . ")");
		  
            //$last_insert_user_id = $this->_db->lastInsertId(); 
            if($add_user)
            {
                echo "A new user has been successfully created";
            }
	}
	
	public function viewUsersById($userid)
	{
		$getUsers = $this->_db->fetchAll("
			SELECT U.firstname, U.lastname, U.nickname, U.password, U.email_address, U.date_created, U.is_login, U.status
			FROM user AS U			
			WHERE U.userid = '" . $userid . "' AND U.userlevel != 'superadmin'
		");
		
		return $getUsers;
	}
	
	public function getUserPermission()
	{
		$getPermission = $this->_db->fetchAll("
			SELECT P.user_type, P.module, P.acl
			FROM permission AS P			
		");
		
		return $getPermission;
	}
	
	public function updateUser($form_values, $userid)
	{
		$firstname = $form_values['firstname'];
		$lastname = $form_values['lastname']; 
		$email = $form_values['email'];
		$user_type = $form_values['userlevel'];
		$status = $form_values['status'];
		try {
			$update_user = $this->_db->query("
				UPDATE user
				SET firstname = '" . $firstname . "', lastname = '" . $lastname . "', email_address = '" . $email . "', date_created = now(), userlevel = '" . $user_type . "', status = '" . $status . "'
				WHERE userid = " . $userid . "
			");
			if($update_user) {
			    echo "User details has been successfully updated";
			}
		} catch (Exception $e) {
			return false;
		}
			
	}
	
	public function deleteUser($user_arr)
	{
		$user_arr = explode("--", $user_arr);
        foreach ($user_arr as $user_entry) {
            if($user_entry != "") {
                $delUser = $this->_db->query("
                    DELETE FROM user
                	WHERE userid = " . $user_entry . "
                ");                
            }  
    	}
    	if($delUser)
        {
            echo "Selected user has been successfully deleted";
        }
	}
	
	public function getUserPermissionByType($usertype)
	{
		$userPermission = $this->_db->fetchAll("
			SELECT module, acl
			FROM permission
			WHERE user_type = '" . $usertype . "'
		");
		
		return $userPermission;
	}
	
	public function createRandomPassword() 
	{
	    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double)microtime()*1000000);
        $i = 0;
        $pass = '' ;
        while ($i <= 7) 
        {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
    }
    
    public function resetPassword($username)
    {
        $random_password = $this->createRandomPassword();
        $reset_password = $this->_db->query("
            UPDATE user 
            SET password = md5('" . $random_password . "')
            WHERE nickname = '" . $username . "'
        ");
        
        if($reset_password)
        {
            echo $username . "-" . $random_password;
        }
    }
    
    public function updateAdminPassword($userid, $curr_pwd, $new_pwd)
    {
        $user_arr = $this->_db->fetchRow("
            SELECT userlevel
            FROM user
            WHERE userid = " . $userid
        );
        
        $userlevel = $user_arr['userlevel'];
        $curr_pwd = md5($curr_pwd);
        $new_pwd = md5($new_pwd);
        
        $record_count = $this->_db->fetchRow("
        					SELECT nickname 
        				 	FROM user
        				 	WHERE password = '" . $curr_pwd . "' 
        				");
        
        if($record_count['nickname'])
        {
        	$reset_password = $this->_db->query("
            	UPDATE user 
            	SET password = '" . $new_pwd . "'
            	WHERE userid = " . $userid . " AND userlevel = '" . $userlevel . "'
        	");
        
        	if($reset_password)
        	{
            	echo "Your Password has been successfully changed.";
        	}
        } else {        	
        	echo "System is unable to find the password you entered. Please provide a valid password to reset.";
        }
    }
}

